// window.onload = function(){
var token=localStorage.getItem('token');
if(token){
    // layer.msg("登陆成功");                     
}else{
    window.location.href="login.html";
}
// url网站域名
var url="http://hengzhi.ayvvv.com";

function sum(arr) {
   var s = 0;
    for (var i=arr.length-1; i>=0; i--) {
        s += arr[i];
    }
    return s;
}
// 商品增加减ajax开始
function change_ajax(id,num) {
    $.ajax({
        url:url+'/api/user/cart/change/'+id,
        dataType:"json",
        type:"post",
        data:{"cart_num": num},
        headers:{
        "X-Token":token,
        },
        async:true,
        success:function(result){
            console.log(result);
        },
        error:function(){
            layer.msg('请稍后重试')
        }
    });
}
// 购物车页面加减ajax结束
// 商品增加减ajax开始
function del_ajax(id) {
    $.ajax({
        url:url+'/api/user/cart/delete',
        dataType:"json",
        type:"post",
        data:{"cart_id": id},
        headers:{
        "X-Token":token,
        },
        async:true,
        success:function(result){
            console.log(result);

        },
        error:function(){
            layer.msg('请稍后重试')
        }
    });
}
// 购物车页面加减ajax结束

function djjj(){

    // 跳转a链接预带值
    let cart_id_arr=[];
    $('.col4').each(function(i,n){
         cart_id_arr.push($(this).attr("cart_id"));
    });   
    cart_id_arr.shift();
    var all_cart_id_str=cart_id_arr.join(",")
    $('.checkout').attr({ href: "flow2.html?sel_id="+all_cart_id_str});
    
    //减少
    $(".reduce_num").click(function(){
        var num=parseInt($(this).next().val())-1;
        var cart_id=parseInt($(this).parent().attr("cart_id"));

        var amount = $(this).parent().find(".amount");
        if (parseInt($(amount).val()) <= 1){
            layer.msg("商品数量最少为1");
        } else{
            change_ajax(cart_id,num);
            $(amount).val(parseInt($(amount).val()) - 1);
        }
        //小计
        var subtotal = parseFloat($(this).parent().parent().find(".col3 span").text()) * parseInt($(amount).val());
        $(this).parent().parent().find(".col5 span").text(subtotal.toFixed(2));
        //总计金额
        var total = 0;
        $(".col5 span").each(function(){
            total += parseFloat($(this).text());
        });

        $("#total").text(Math.round(total.toFixed(2)));
    });

    //增加
    $(".add_num").click(function(){
        var stock = parseInt($(this).attr("stock"));
        var num=parseInt($(this).prev().val())+1;
        var cart_id=parseInt($(this).parent().attr("cart_id"));

        if (stock>=num){
            
            var amount = $(this).parent().find(".amount");

            $(amount).val(parseInt($(amount).val()) + 1);
            
            //小计
            var subtotal = parseFloat($(this).parent().parent().find(".col3 span").text()) * parseInt($(amount).val());
            $(this).parent().parent().find(".col5 span").text(subtotal.toFixed(2));
            //总计金额
            var total = 0;
            $(".col5 span").each(function(){
                total += parseFloat($(this).text());
            });

            $("#total").text(Math.round(total.toFixed(2)));

            change_ajax(cart_id,num);
        }else{
            layer.msg("补货中")

        }



    });

    //直接输入
    $(".amount").blur(function(){
        var num=parseInt($(this).val());
        var cart_id=parseInt($(this).parent().attr("cart_id"));
        var stock = parseInt($(this).next().attr("stock"));

        if (num < 1){
            layer.msg("商品数量最少为1");
            $(this).val(1);
            change_ajax(cart_id,1);
        }
        if (num > stock){
            layer.msg("此商品库存不足");
            $(this).val(stock);
        }else{
            change_ajax(cart_id,num);


        }
        //小计
        var subtotal = parseFloat($(this).parent().parent().find(".col3 span").text()) * parseInt($(this).val());
        $(this).parent().parent().find(".col5 span").text(subtotal.toFixed(2));
        //总计金额
        var total = 0;
        $(".col5 span").each(function(){
            total += parseFloat($(this).text());
        });

        $("#total").text(Math.round(total.toFixed(2)));

    });

    //删除
    $(".col6").click(function(){
        let cart_id_arr=[];
        var cart_id=$(this).parent().children('.col4').attr("cart_id");
        $(this).parent().empty();
        cart_id_arr.push(cart_id);
        del_ajax(cart_id_arr);
        layer.msg("删除成功");
      
        //总计金额
        var total = 0;
        $(".col5 span").each(function(){
            total += parseFloat($(this).text());
        });

        $("#total").text(Math.round(total.toFixed(2)));
        

    });

    //一键清空
    $(".delshopcar").click(function(){

        // del_ajax(cart_id_arr);
        // $('#store_car').children().empty();
        // layer.msg("清空购物车成功");
        // $('#total').text(0)
        alert("一键清空");

    });

    // 复选框单选
    $(".is_sel").click(function(){
         var cart_id=$(this).parent().parent().children('.col4').attr("cart_id");
         var num=parseInt($(this).parent().parent().children('.col4').children('.amount').val());
         
         if ($(this).prop("checked")) {
            cart_id_arr.push(cart_id);
         }else{
            cart_id_arr.splice($.inArray(cart_id,cart_id_arr),1);

         }
        all_cart_id_strs=cart_id_arr.join(",")

        $('.checkout').attr({ href: "flow2.html?sel_id="+all_cart_id_strs});

    });
    // 复选框全选
    $(".allsel").click(function(){

        var check=$('.is_sel').is(':checked');
       if(check){
            $("input[name='is_sel']").attr("checked",false);

            $('.checkout').attr({ href: "flow2.html"});

       
            $("#total").text(0);
      
       }else{
            $("input[name='is_sel']").attr("checked",true);

            $('.checkout').attr({ href: "flow2.html?sel_id="+all_cart_id_str});

      
            //总计金额
            var total = 0;
            $(".col5 span").each(function(){
                total += parseFloat($(this).text());
            });
            $("#total").text(Math.round(total.toFixed(2)));
    
        }   
   

    });

};
 
                     

// 购物车结果加载开始
$.ajax({
    url:url+'/api/user/cart/lst',
    dataType:"json",
    type:"get",
    headers:{
    "X-Token":token,
    },
    async:true,
    success:function(result){
        console.log(result)
        var all_list=result.data.list;

        let allpirce=[];

        
        for (var i = 0; i < all_list.length; i++) {
            var store_list=all_list[i].list;
            for (var j = 0; j < store_list.length; j++) {
                // console.log(store_list[j])
                var  subtotal=store_list[j].product.price*store_list[j].cart_num;
                 $('#store_car').append(`<tr>
                      
 
                    <td class="col0"><input class="is_sel" type="checkbox" name="is_sel" title="选中状态" checked ='checked'></td>
   
                    <td class="col1"><a href="goods.html?product_id=`+store_list[j].product_id+`"><img src="`+store_list[j].product.image+`" alt="" /></a>  <strong><a href="goods.html?product_id=`+store_list[j].product_id+`">`+store_list[j].product.store_name+`</a></strong></td>
                    <td class="col2"> <p>`+store_list[j].productAttr.sku+`</p> </td>

                    <td class="col3">￥<span>`+store_list[j].product.price+`</span></td>
                    <td class="col4" cart_id="`+store_list[j].cart_id+`"> 
                        <a href="javascript:;" class="reduce_num"></a>
                        <input type="text" name="amount" value="`+store_list[j].cart_num+`" class="amount">
                        <a href="javascript:;" class="add_num" stock="`+store_list[j].productAttr.stock+`"></a>
                    </td>
                    <td class="col5">￥<span>`+subtotal+`</span></td>
                    <td class="col6"><a href="#">删除</a></td>

                </tr>`);
                // console.log(store_list[j].productAttr.stock);
                allpirce.push(subtotal);
            }
            
        };
         djjj()

         $("#total").text(Math.round(sum(allpirce)*100)/100);

    },
    error:function(){
        layer.msg('请稍后重试')
    }
// 购物车结果加载结束                     


});




















// }